package org.jeecg.modules.spider;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.exception.RequestException;
import org.jeecg.common.util.RestUtil;
import org.jeecg.config.spider.Motuo58Config;
import org.jeecg.modules.brand.entity.IBrand;
import org.jeecg.modules.brand.mapper.IBrandMapper;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.List;

/**
 * 58motuo爬虫
 * @author: lcs
 * @date: 2024年06月02日 17:04
 */
@Slf4j
@Component
public class Motuo58Spider extends ServiceImpl<IBrandMapper, IBrand> {

    public static final String DATA = "data";
    public static final String MSG = "msg";
    @Resource
    private Motuo58Config motuo58Config;

    @Resource
    private IBrandMapper iBrandMapper;

    /**
     *  品牌列表抓取
     */
    @Transactional(rollbackFor = Exception.class)
    public void brandListUrl() {
//        定义日期
        LocalDate versionDate = LocalDate.now();
//        校验产品是否已经存在
        LambdaQueryWrapper<IBrand> queryWrapper = Wrappers.lambdaQuery(IBrand.class)
                .eq(IBrand::getVersionDate, versionDate);
        if (iBrandMapper.selectCount(queryWrapper) > 0) {
            log.info("今日产品已同步，无需同步");
            return;
        }
        log.info("开始抓取产品");
        JSONObject jsonObject = RestUtil.get(motuo58Config.getBrandListUrl());
//        校验是否成功
        verifyRequest(jsonObject);

//        转换为数据库对象
        JSONArray jsonArray = jsonObject.getJSONArray(DATA);

        List<IBrand> iBrands = jsonArray.toJavaList(IBrand.class);
        for (IBrand iBrand : iBrands) {
            iBrand.setVersionDate(versionDate);
        }
        saveBatch(iBrands);
        log.info("抓取产品-完成");
    }

    /**
     * 验证请求是否成功
     */
    public void verifyRequest(JSONObject jsonObject) {
        if (jsonObject.getInteger("code") != 0) {
            throw new RequestException("58motuo-api调用失败：" + jsonObject.get(MSG));
        }
    }
}
